package com.iknow.http;

import com.iknow.util.Loger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class Response
{
  private static final boolean DEBUG = 1;
  private static final String TAG = "Response";
  private static ThreadLocal<DocumentBuilder> builders = new ThreadLocal()
  {
    protected DocumentBuilder initialValue()
    {
      DocumentBuilder localDocumentBuilder;
      try
      {
        localDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        return localDocumentBuilder;
      }
      catch (ParserConfigurationException localParserConfigurationException)
      {
        throw new ExceptionInInitializerError(localParserConfigurationException);
      }
    }
  };
  private static Pattern escaped = Pattern.compile("&#([0-9]{3,5});");
  private HttpURLConnection con;
  private String contentEncoding;
  private InputStream is;
  private String mUrlID;
  private HttpResponse response;
  private Document responseAsDocument = null;
  private String responseAsString = null;
  private Header[] responseHeader;
  private int statusCode;
  private StatusLine statusLine;
  private boolean streamConsumed = false;

  Response(String paramString)
  {
    this.responseAsString = paramString;
  }

  public Response(HttpResponse paramHttpResponse, String paramString)
    throws IOException
  {
    this.response = paramHttpResponse;
    this.statusLine = paramHttpResponse.getStatusLine();
    this.statusCode = this.statusLine.getStatusCode();
    this.responseHeader = paramHttpResponse.getAllHeaders();
    HttpEntity localHttpEntity = paramHttpResponse.getEntity();
    this.is = localHttpEntity.getContent();
    Header localHeader = localHttpEntity.getContentEncoding();
    if ((this.is != null) && (localHeader != null) && ("gzip".equals(localHeader.getValue())))
      this.is = new GZIPInputStream(this.is);
    this.mUrlID = paramString;
  }

  private void log(String paramString)
  {
    Loger.i("Response", paramString);
  }

  private void log(String paramString1, String paramString2)
  {
    log(paramString1 + paramString2);
  }

  public static String unescape(String paramString)
  {
    Matcher localMatcher = escaped.matcher(paramString);
    StringBuffer localStringBuffer = new StringBuffer();
    while (true)
    {
      if (!(localMatcher.find()))
      {
        localMatcher.appendTail(localStringBuffer);
        return localStringBuffer.toString();
      }
      localMatcher.appendReplacement(localStringBuffer, Character.toString((char)Integer.parseInt(localMatcher.group(1), 10)));
    }
  }

  public Document asDocument()
    throws ResponseException
  {
    if (this.responseAsDocument == null);
    try
    {
      this.responseAsDocument = ((DocumentBuilder)builders.get()).parse(new ByteArrayInputStream(asString().getBytes("UTF-8")));
      return this.responseAsDocument;
    }
    catch (SAXException localSAXException)
    {
      throw new ResponseException("The response body was not well-formed:\n" + this.responseAsString, localSAXException);
    }
    catch (IOException localIOException)
    {
      throw new ResponseException("There's something with the connection.", localIOException);
    }
    catch (DOMException localDOMException)
    {
      throw new ResponseException("The response body was not well-formed:\n" + this.responseAsString, localDOMException);
    }
  }

  public JSONArray asJSONArray()
    throws ResponseException
  {
    JSONArray localJSONArray;
    try
    {
      localJSONArray = new JSONArray(asString());
      return localJSONArray;
    }
    catch (Exception localException)
    {
      throw new ResponseException(localException.getMessage() + ":" + this.responseAsString, localException);
    }
  }

  public JSONObject asJSONObject()
    throws ResponseException
  {
    JSONObject localJSONObject;
    try
    {
      localJSONObject = new JSONObject(asString());
      return localJSONObject;
    }
    catch (JSONException localJSONException)
    {
      throw new ResponseException(localJSONException.getMessage() + ":" + this.responseAsString, localJSONException);
    }
  }

  public InputStreamReader asReader()
  {
    InputStreamReader localInputStreamReader;
    try
    {
      localInputStreamReader = new InputStreamReader(this.is, "UTF-8");
      return localInputStreamReader;
    }
    catch (UnsupportedEncodingException localUnsupportedEncodingException)
    {
      localInputStreamReader = new InputStreamReader(this.is);
    }
  }

  public InputStream asStream()
  {
    if (this.streamConsumed)
      throw new IllegalStateException("Stream has already been consumed.");
    return this.is;
  }

  // ERROR //
  public String asString()
    throws ResponseException
  {
    // Byte code:
    //   0: aload_0
    //   1: getfield 58	com/iknow/http/Response:responseAsString	Ljava/lang/String;
    //   4: ifnonnull +105 -> 109
    //   7: aload_0
    //   8: invokevirtual 269	com/iknow/http/Response:asStream	()Ljava/io/InputStream;
    //   11: astore 4
    //   13: aload 4
    //   15: ifnonnull +8 -> 23
    //   18: aconst_null
    //   19: astore_1
    //   20: goto +142 -> 162
    //   23: new 271	java/io/BufferedReader
    //   26: dup
    //   27: new 255	java/io/InputStreamReader
    //   30: dup
    //   31: aload 4
    //   33: ldc 211
    //   35: invokespecial 258	java/io/InputStreamReader:<init>	(Ljava/io/InputStream;Ljava/lang/String;)V
    //   38: invokespecial 274	java/io/BufferedReader:<init>	(Ljava/io/Reader;)V
    //   41: astore 5
    //   43: new 157	java/lang/StringBuffer
    //   46: dup
    //   47: invokespecial 158	java/lang/StringBuffer:<init>	()V
    //   50: astore 6
    //   52: aload 5
    //   54: invokevirtual 277	java/io/BufferedReader:readLine	()Ljava/lang/String;
    //   57: astore 7
    //   59: aload 7
    //   61: ifnonnull +56 -> 117
    //   64: aload_0
    //   65: aload 6
    //   67: invokevirtual 169	java/lang/StringBuffer:toString	()Ljava/lang/String;
    //   70: putfield 58	com/iknow/http/Response:responseAsString	Ljava/lang/String;
    //   73: aload_0
    //   74: aload_0
    //   75: getfield 58	com/iknow/http/Response:responseAsString	Ljava/lang/String;
    //   78: invokestatic 279	com/iknow/http/Response:unescape	(Ljava/lang/String;)Ljava/lang/String;
    //   81: putfield 58	com/iknow/http/Response:responseAsString	Ljava/lang/String;
    //   84: aload 4
    //   86: invokevirtual 284	java/io/InputStream:close	()V
    //   89: aload_0
    //   90: iconst_1
    //   91: putfield 60	com/iknow/http/Response:streamConsumed	Z
    //   94: getstatic 290	com/iknow/IKnow:mCacheSystem	Lcom/iknow/file/CacheSystem;
    //   97: aload_0
    //   98: getfield 125	com/iknow/http/Response:mUrlID	Ljava/lang/String;
    //   101: aload_0
    //   102: getfield 58	com/iknow/http/Response:responseAsString	Ljava/lang/String;
    //   105: invokevirtual 296	com/iknow/file/CacheSystem:saveFile	(Ljava/lang/String;Ljava/lang/String;)I
    //   108: pop
    //   109: aload_0
    //   110: getfield 58	com/iknow/http/Response:responseAsString	Ljava/lang/String;
    //   113: astore_1
    //   114: goto +48 -> 162
    //   117: aload 6
    //   119: aload 7
    //   121: invokevirtual 299	java/lang/StringBuffer:append	(Ljava/lang/String;)Ljava/lang/StringBuffer;
    //   124: ldc_w 301
    //   127: invokevirtual 299	java/lang/StringBuffer:append	(Ljava/lang/String;)Ljava/lang/StringBuffer;
    //   130: pop
    //   131: goto -79 -> 52
    //   134: astore_3
    //   135: new 192	ResponseException
    //   138: dup
    //   139: aload_3
    //   140: invokevirtual 302	java/lang/NullPointerException:getMessage	()Ljava/lang/String;
    //   143: aload_3
    //   144: invokespecial 227	ResponseException:<init>	(Ljava/lang/String;Ljava/lang/Exception;)V
    //   147: athrow
    //   148: astore_2
    //   149: new 192	ResponseException
    //   152: dup
    //   153: aload_2
    //   154: invokevirtual 303	IOException:getMessage	()Ljava/lang/String;
    //   157: aload_2
    //   158: invokespecial 227	ResponseException:<init>	(Ljava/lang/String;Ljava/lang/Exception;)V
    //   161: athrow
    //   162: aload_1
    //   163: areturn
    //
    // Exception table:
    //   from	to	target	type
    //   7	109	134	java/lang/NullPointerException
    //   117	131	134	java/lang/NullPointerException
    //   7	109	148	IOException
    //   117	131	148	IOException
  }

  public void disconnect()
  {
    this.con.disconnect();
  }

  public String getResponseAsString()
  {
    return this.responseAsString;
  }

  public String getResponseHeader(String paramString)
  {
    String str;
    if (this.response != null)
    {
      Header[] arrayOfHeader = this.response.getHeaders(paramString);
      if (arrayOfHeader.length > 0)
        str = arrayOfHeader[0].getValue();
    }
    while (true)
    {
      return str;
      str = null;
    }
  }

  public int getStatusCode()
  {
    return this.statusCode;
  }

  public void setResponseAsString(String paramString)
  {
    this.responseAsString = paramString;
  }

  public void setStatusCode(int paramInt)
  {
    this.statusCode = paramInt;
  }

  public String toString()
  {
    return "Response [statusCode=" + this.statusCode + ", responseAsDocument=" + this.responseAsDocument + ", responseAsString=" + this.responseAsString + ", is=" + this.is + ", con=" + this.con + ", streamConsumed=" + this.streamConsumed + ", response=" + this.response + ", statusLine=" + this.statusLine + ", responseHeader=" + Arrays.toString(this.responseHeader) + "]";
  }
}